package com.googlecode.droidircclient;
/* =================================================
 * Droid IRC Client
 * Authors: Kevin Garton, Dennis McWherter
 * 12 September 2011
 * =================================================*/

import android.view.KeyEvent;

import android.app.Activity;

import android.view.*;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;

import com.googlecode.droidircclient.Sockets.*;

public class InputKeyListener implements OnKeyListener {
	private EditText Input;
	private ClientSocket Sock;
	private DroidIRCClientActivity Activity;
	

	/**
	 * Constructor
	 */


	public InputKeyListener(View in, View out, ClientSocket sock, Activity activity) {
		Input    = (EditText)in;
		Sock     = sock;
		Activity = (DroidIRCClientActivity)activity; 
	}

	@Override
	public boolean onKey(View v, int keyCode, KeyEvent event) {
		String tmp = null;
    	if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER){
    		tmp = Input.getText().toString() + "\n";//If no newline, server won't recognize
    		/* A frontslash indicates that the message is intended to be sent directly to the server.*/
    		if(tmp.charAt(0)=='/'){
    			String[] words = tmp.split(" ");
        		if(tmp.substring(1,6).toUpperCase().equals("PART")){
        			if(words[1] != null){
        				Sock.write(tmp.substring(1));
        				Activity.removeViewAt(Activity.findView(words[1]));
        			}
        			else{
        				Sock.write(tmp.substring(1) + " " + Activity.getCurrentViewName()); // Simple socket implementation
        				Activity.removeCurrentView();
        			}
        		}
        		else
        			Sock.write(tmp.substring(1)); // Simple socket implementation
        		Input.setText("");
        		return true;
    		}    		
    		
    		
    		String targe = Activity.getCurrentView().getName(); 
    		Activity.updateOutput(tmp,targe);
    		String writer = "PRIVMSG " + targe + " :"+ tmp;
    		Sock.write(writer); // Simple socket implementation
    		Activity.updateHistory(tmp);
    		Input.setText("");
    		Activity.updateScroll();
    	return true;
    	}
    	return false;
	}
}
